"use strict";
const moment = require("moment");
const { Model } = require("sequelize");
module.exports = (sequelize, DataTypes) => {
  class Menu extends Model {
    static associate(models) {
      models.Menu.belongsToMany(models.Role, {
        through: models.RolesMenus,
        foreignKey: "menuId",
        as: "roles",
      });
    }
  }
  Menu.init(
    {
      pid: DataTypes.INTEGER,
      name: {
        type: DataTypes.STRING,
        allowNull: false,
        validate: {
          notNull: { msg: "菜单名必须填写。" },
          notEmpty: { msg: "菜单名不能为空。" },
          len: { args: [1, 45], msg: "菜单名长度必须是1 ~ 45之间。" },
          async isUnique(value) {
            const menu = await Menu.findOne({ where: { name: value } });
            if (menu) {
              throw new Error("菜单名已经存在。");
            }
          },
        },
      },
      menuType: {
        type: DataTypes.TINYINT,
        allowNull: false,
        validate: {
          notNull: { msg: "菜单类型必须填写。" },
          notEmpty: { msg: "菜单类型不能为空。" },
          isIn: {
            args: [[0, 1]],
            msg: "菜单类型的值必须是，菜单：0 按钮：1。",
          },
        },
      },
      title: DataTypes.STRING,
      path: DataTypes.STRING,
      component: DataTypes.STRING,
      redirect: DataTypes.STRING,
      icon: DataTypes.STRING,
      sort: DataTypes.INTEGER,
      position: DataTypes.INTEGER,
      hidden: DataTypes.BOOLEAN,
      affix: DataTypes.BOOLEAN,
      noTagView: DataTypes.BOOLEAN,
      alwaysShow: DataTypes.BOOLEAN,
      noCache: DataTypes.BOOLEAN,
      createdAt: {
        type: DataTypes.DATE,
        get() {
          return moment(this.getDataValue("createdAt")).format(
            "YYYY-MM-DD HH:mm:ss"
          );
        },
      },
      updatedAt: {
        type: DataTypes.DATE,
        get() {
          return moment(this.getDataValue("updatedAt")).format(
            "YYYY-MM-DD HH:mm:ss"
          );
        },
      },
    },
    {
      sequelize,
      modelName: "Menu",
    }
  );
  return Menu;
};
